﻿package com.find.memories.photoviewer;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.find.memories.ApplicationPool;
import com.find.memories.R;
import com.find.memories.gallery.PhotoItem;
import com.find.memories.photoviewer.CustomViewPager.ItemInfo;
import com.find.memories.photoviewer.CustomViewPager.OnPageChangeListener;
import com.find.memories.photoviewer.PhotoViewerPagerAdapter.AdapterPrimaryItemListener;

/**
 * PhotoViewer Main Activity입니다.<br>
 * GNB Activity를 상속 받았지만 관련하여 연관되는 기능은 없습니다.
 * @author Jang
 *
 */
public class PhotoViewerActivity extends Activity {

    final static String TAG = "PhotoViewerActivity";

    public static final String KEY_DATA_LIST                            = "data_list";
    public static final String START_POSITION                          = "start_position";
    public static final int     HARDWARE_ACCELERATE             = 16777216;
    
    public static final int SLIDE_LEFT 	=	1;
    public static final int SLIDE_RIGHT	=	2;
    public static final int SLIDE_ALL 	=	3;

    public static final int FIX_WIDTH = 480;

    private static final long MAX_IMAGE_SIZE = 2500000;

    final static int PHONE_PICTURE_WIDTH = 800;
    final static int PHONE_PICTURE_HEIGHT = 600;

    public enum TouchMode {
        SLIDE_MODE, THUMBNAIL_MODE;
    }
    
    private Context mContext;

    private RelativeLayout mTopMenuLayout;
    private TextView mTopDateIndicate;
    private TextView mTopCountIndicate;
    
    private PhotoViewerPager mBodyPager;
    private PhotoViewerPagerAdapter mAdapter;

    private GestureDetector mGesture;
    
    private TouchMode mCurrentTouchMode = TouchMode.SLIDE_MODE;

    private Handler mHandler = new Handler();

    private LayoutInflater mInflater;

    ArrayList<PhotoItem> mPhotoList = null;
    private int mCurrentPosition = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if(android.os.Build.VERSION.SDK_INT >= 11) { 
            getWindow().addFlags(HARDWARE_ACCELERATE);
        }

        mContext = this;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.photo_viewer_activity);

		init();
	}
	
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        if (mAdapter != null) {
            mAdapter.setZoomMode(false, ThumbnailView.MIN_ZOOM, new Point());
            this.setTouchMode(TouchMode.SLIDE_MODE);
        }
        
        super.onResume();
    }
    
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    protected void onDestroy() {
        super.onDestroy();
    };

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        if (mAdapter != null)
            mAdapter.notifyDataSetChanged(true);
    }

    private void init() {
        setLayout();

        Intent intent = getIntent();
        
        ApplicationPool pool = (ApplicationPool)getApplicationContext();
        
        mCurrentPosition = intent.getIntExtra(START_POSITION, 0);
        mPhotoList = (ArrayList<PhotoItem>)pool.getExtra(KEY_DATA_LIST, intent);
        
        mInflater = LayoutInflater.from(this);
        mAdapter = new PhotoViewerPagerAdapter(this, mInflater);
        mAdapter.setSlideStateListener(new SlideStateListener() {

            @Override
            public void SlideState(int which) {
                // TODO Auto-generated method stub
                switch (which) {
                    case PhotoViewerActivity.SLIDE_LEFT:
                        setTouchMode(TouchMode.SLIDE_MODE);
                        break;
                    case PhotoViewerActivity.SLIDE_RIGHT:
                        setTouchMode(TouchMode.SLIDE_MODE);
                        break;
                    case PhotoViewerActivity.SLIDE_ALL:
                        setTouchMode(TouchMode.SLIDE_MODE);
                        break;
                    default:
                        break;
                }
            }
        });
        mGesture = new GestureDetector(this, mGesListener);

        mAdapter.setPhotoList(mPhotoList.size(), mPhotoList);
        mBodyPager.setAdapter(mAdapter);
        mBodyPager.setPageScrollStop(false);
        mBodyPager.setCurrentItem(mCurrentPosition);
        
        setCountIndicator(mCurrentPosition+1);
        setDataIndicator(((PhotoItem)mPhotoList.get(mCurrentPosition)).regDate);
        
        mBodyPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageScrollStateChanged(int state) {
                // TODO Auto-generated method stub
                if (null != mAdapter && null != mBodyPager && state != PhotoViewerPager.SCROLL_STATE_DRAGGING) {
                    View view = (View) mBodyPager.getCurrentObject();
                    if (view != null) {
                        PhotoViewerBodyInterface bodyInterface = (PhotoViewerBodyInterface) view.getTag();
                        if (null != bodyInterface && bodyInterface.isZoomMode()) {
                            setTouchMode(TouchMode.THUMBNAIL_MODE);
                        } else {
                            setTouchMode(TouchMode.SLIDE_MODE);
                        }
                    }
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageSelected(int position) {
            }
        });
        
        /**
         * 현재 보이고 있는 주요 Body가 생성되면 Listener로 전달받는다.
         */
        mAdapter.setPrimaryItemListener(new AdapterPrimaryItemListener() {

            @Override
            public void createdPrimaryItem(int position) {

                if (!PhotoViewerActivity.this.isFinishing()) {
                    if (position != mCurrentPosition || (mAdapter!= null && mPhotoList.size() != mAdapter.getCount())) {
                        
                        if (mBodyPager != null) {
                            ArrayList<ItemInfo> list = mBodyPager.getPagerItemList();
                            for (int i=0; i < list.size(); i++) {
                                View view = (View) list.get(i).object;
                                if (view != null) {
                                    PhotoViewerBodyInterface bodyInterface = (PhotoViewerBodyInterface) view.getTag();
                                    if (null != bodyInterface && bodyInterface.isZoomMode()) {
                                        setTouchMode(TouchMode.THUMBNAIL_MODE);
                                        bodyInterface.setZoomMode(false, ThumbnailView.MIN_ZOOM, new Point());
                                        setTouchMode(TouchMode.SLIDE_MODE);
                                    }
                                }
                            }
                        }
                        
                        setCountIndicator(position + 1);
                        setDataIndicator(((PhotoItem)mPhotoList.get(position)).regDate);
                        
                    }

                    mCurrentPosition = position;
                }
            }
        });
    }

    private void setLayout() {
        mTopMenuLayout = (RelativeLayout)findViewById(R.id.photo_viewer_menu_top_layout);
        mTopDateIndicate = (TextView)findViewById(R.id.photo_viewer_menu_indicate_date);
        mTopCountIndicate = (TextView)findViewById(R.id.photo_viewer_menu_indicate_count);
        mBodyPager = (PhotoViewerPager)findViewById(R.id.photo_viewer_body_layout_pager);		
	}

    /**
     * 현재 Touch모드 설정
     * @param mode
     */
    public void setTouchMode(TouchMode mode) {
        mCurrentTouchMode = mode;
        if (mCurrentTouchMode == TouchMode.SLIDE_MODE) {
            mBodyPager.setEnableScroll(true);
        } else if (mCurrentTouchMode == TouchMode.THUMBNAIL_MODE) {
            mBodyPager.setEnableScroll(false);
        }
    }
    
    /**
     * 포토뷰어 Gesture동작 관련
     */
    SimpleOnGestureListener mGesListener = new GestureDetector.SimpleOnGestureListener() {

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            
            return false;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            
            return super.onSingleTapConfirmed(e);
        }

        @Override
        public void onShowPress(MotionEvent e) {
            

        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            
            if (mBodyPager.getCurrentState() == PhotoViewerPager.SCROLL_STATE_IDLE) {
                if (mAdapter != null) {
                    Point point = new Point((int)e.getX(), (int)e.getY());
                    if (mAdapter.isMaxDoubleTapZoom()) {
                        mAdapter.setZoomMode(false, ThumbnailView.MIN_ZOOM, point);
                        setTouchMode(TouchMode.SLIDE_MODE);
                    } else {
                        mAdapter.setZoomMode(true, ThumbnailView.DOUBLE_TAP, point);
                        setTouchMode(TouchMode.THUMBNAIL_MODE);
                    }
                }
            }
            return super.onDoubleTap(e);
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                float distanceX, float distanceY) {
            
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
            
            return false;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            
            return false;
        }
    };

    public PhotoItem getCurrentPhotoItem(int position) {
        PhotoItem item = (PhotoItem)mPhotoList.get(position);
        return item;
    }

    @Override
    public void onLowMemory() {
        
        super.onLowMemory();
        System.gc();
    }

    public PhotoItem getCurrentPhotoItem (){
        PhotoItem photoItem = null;
        if (mBodyPager != null) {
            ArrayList<ItemInfo> list = mBodyPager.getPagerItemList();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).position == mCurrentPosition) {
                    View view = (View) list.get(i).object;
                    if (view != null) {
                        photoItem = (PhotoItem) view.getTag();
                    }
                }
            }
        }
        return photoItem;
    }

    private void setDataIndicator(String date) {
        
        String strDate = new SimpleDateFormat("yyyy.MM.dd").format(Long.valueOf(date));
        
        if (mTopDateIndicate != null) {
            mTopDateIndicate.setText(strDate);
        }
    }
    
    /**
     * 사진의 총 장수와 현재 장수를 출력한다.
     * @param position
     */
    private void setCountIndicator(int position) {
        if (mTopCountIndicate != null) {
            String text = position + "/" + mAdapter.getCount();
            mTopCountIndicate.setText(text);
        }

    }
    
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        if (ev.getPointerCount() > 1 && mBodyPager.getCurrentState() == PhotoViewerPager.SCROLL_STATE_IDLE) {
            Point point = new Point((int)ev.getX(), (int)ev.getY());
            mAdapter.setZoomMode(true, ThumbnailView.NORMAL, point);
            this.setTouchMode(TouchMode.THUMBNAIL_MODE);
        }
        
        mGesture.onTouchEvent(ev);
        
        return super.dispatchTouchEvent(ev);
    }
}
